﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using TBlog.Web.Data;
using TBlog.Web.Models;
using EntityFramework.Extensions;
using System.Linq.Expressions;
namespace TBlog.Web.Repository
{
    public class EFRepository<T> : IRepository<T> where T : BaseEntity
    {
        readonly IDbContext _context;
        IDbSet<T> _entities;
        public EFRepository(IDbContext context)
        {
            _context = context;
        }
        protected IDbSet<T> Entities
        {
            get
            {
                if (_entities == null)
                    return _entities = _context.DbSet<T>();
                return _entities;
            }
        }
        protected IQueryable<T> Table
        {
            get { return Entities; }
        }


        public int Insert(T Entity)
        {
             Entities.Add(Entity);
           
            return _context.SaveChanges();
        }

        public virtual int Update(T Entity)
        {


            return _context.SaveChanges();

        }

        public int Delete(int ID)
        {

            return Entities.Where(A => A.ID == ID).Delete();
            // _context.SaveChanges();
        }

        public System.Threading.Tasks.Task<int> InsertAsync(T Entity)
        {
            Entities.Add(Entity);
            return _context.SaveChangesAsync();
        }

        public T GetByID(int ID)
        {
            return Entities.Where(T => T.ID == ID).SingleOrDefault();

        }

        public IQueryable<T> GetAll()
        {
            return Entities;
        }
    }
}